package org.jeecg.modules.outOrder.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.Inventory.entity.Inventory;
import org.jeecg.modules.Inventory.service.IInventoryService;
import org.jeecg.modules.basicSku.entity.BasicSku;
import org.jeecg.modules.basicSku.service.IBasicSkuService;
import org.jeecg.modules.inOrder.service.IInOrderService;
import org.jeecg.modules.inOrder.service.IInOrderZiService;
import org.jeecg.modules.operationLog.entity.OperationLog;
import org.jeecg.modules.operationLog.service.IOperationLogService;
import org.jeecg.modules.outOrder.entity.OutOrder;
import org.jeecg.modules.outOrder.entity.OutOrderZi;
import org.jeecg.modules.outOrder.service.IOutOrderService;
import org.jeecg.modules.outOrder.service.IOutOrderZiService;
import org.jeecg.modules.outOrder.vo.OutOrderPage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Description: 出库单
 * @Author: jeecg-boot
 * @Date: 2024-06-27
 * @Version: V1.0
 */
@Api(tags = "出库单")
@RestController
@RequestMapping("/outOrder/outOrder")
@Slf4j
public class OutOrderController {
    @Autowired
    private IOutOrderService outOrderService;
    @Autowired
    private IOutOrderZiService outOrderZiService;
    @Autowired
    private IInventoryService inventoryService;
    @Autowired
    private IOperationLogService operationLogService;
    @Autowired
    private IInOrderService inOrderService;
    @Autowired
    private IInOrderZiService inOrderZiService;
    @Autowired
    private IBasicSkuService basicSkuService;

    /**
     * 分页列表查询
     *
     * @param outOrder
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "出库单-分页列表查询")
    @ApiOperation(value = "出库单-分页列表查询", notes = "出库单-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(OutOrder outOrder,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<OutOrder> queryWrapper = QueryGenerator.initQueryWrapper(outOrder, req.getParameterMap());
        if ((outOrder.getNum() != null && !outOrder.getNum().isEmpty()) || (outOrder.getSkucode() != null && !outOrder.getSkucode().isEmpty()) || (outOrder.getSkuname() != null && !outOrder.getSkuname().isEmpty()) || (outOrder.getCustomername() != null && !outOrder.getCustomername().isEmpty())) {
            LambdaQueryWrapper<OutOrderZi> wrapper = new LambdaQueryWrapper<>();
            if ((outOrder.getSkucode() != null && !outOrder.getSkucode().isEmpty())) {
                wrapper.eq(OutOrderZi::getSkuCode, outOrder.getSkucode());
            }
            if ((outOrder.getNum() != null && !outOrder.getNum().isEmpty())) {
                wrapper.eq(OutOrderZi::getNumber, outOrder.getNum());
            }
            if ((outOrder.getSkuname() != null && !outOrder.getSkuname().isEmpty())) {
                wrapper.eq(OutOrderZi::getSkuName, outOrder.getSkuname());
            }
            if ((outOrder.getCustomername() != null && !outOrder.getCustomername().isEmpty())) {
                wrapper.eq(OutOrderZi::getCustomer, outOrder.getCustomername());
            }
            List<String> ids = outOrderZiService.list(wrapper).stream().map(OutOrderZi::getOutOrderId).collect(Collectors.toList());
            if (ids.isEmpty()) {
                return Result.OK(new Page<OutOrder>());
            } else {
                queryWrapper.in("id", ids);
            }
        }
        Page<OutOrder> page = new Page<OutOrder>(pageNo, pageSize);
        IPage<OutOrder> pageList = outOrderService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    @PostMapping("/confirm")
    public Result<?> confirm(@RequestBody OutOrder outOrder) {
        OutOrder byId = outOrderService.getById(outOrder.getId());
        if (byId == null) {
            return Result.error("未找到对应数据");
        }
        if (byId.getStatus() == 1) {
            return Result.error("该出库单已出库，请勿重复操作");
        }
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<OutOrderZi> outOrderZis = outOrderZiService.selectByMainId(byId.getId());
        List<OperationLog> operationLogs = new ArrayList<>();
        List<Inventory> inventories = new ArrayList<>();
        for (OutOrderZi outOrderZi : outOrderZis) {
            String inventoryId = outOrderZi.getInventoryId();
            if (inventoryId != null && !inventoryId.isEmpty()) {
                Result<Object> result = getObjectResult(outOrderZi, inventoryId, user, operationLogs, inventories);
                if (result != null) return result;
            }
        }
        inventoryService.updateBatchById(inventories);
        byId.setStatus(1);
        byId.setRealname(user.getRealname());
        outOrderService.updateById(byId);
        operationLogService.saveBatch(operationLogs);
        return Result.OK("出库成功", null);
    }

    private @Nullable Result<Object> getObjectResult(OutOrderZi outOrderZi, String inventoryId, LoginUser user, List<OperationLog> operationLogs, List<Inventory> inventories) {
        Inventory inventory = inventoryService.getById(inventoryId);
        if (inventory.getStatus() == 1) {
            return Result.error("库存错误");
        }
        int stock = inventory.getNumber();
        int number = outOrderZi.getNumber();
        if (number > stock) {
            return Result.error("品番【" + outOrderZi.getSkuCode() + "】库存不足");
        }
        OperationLog operationLog = new OperationLog();
        int i = stock - number;
        inventory.setNumber(i);
        if (i <= 0) {
            inventory.setStatus(1);
        }
        operationLog.setNewNumber(i);
        operationLog.setSkuCode(outOrderZi.getSkuCode()).setSkuName(outOrderZi.getSkuName())
                .setNumber(outOrderZi.getNumber()).setOperationTime(new Date())
                .setOperationType("出库").setOperator(user.getRealname())
                .setLocation(outOrderZi.getLocation()).setInTime(outOrderZi.getInTime());
        operationLogs.add(operationLog);
        inventories.add(inventory);
        return null;
    }

    /**
     * 添加
     *
     * @param outOrderPage
     * @return
     */
    @AutoLog(value = "出库单-添加")
    @ApiOperation(value = "出库单-添加", notes = "出库单-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody OutOrderPage outOrderPage) {
        List<BasicSku> basicSkus = basicSkuService.list();
        Set<String> collect = basicSkus.stream().map(BasicSku::getSkuCode).collect(Collectors.toSet());
        List<OutOrderZi> outOrderZiList = outOrderPage.getOutOrderZiList();
        List<OutOrderZi> addList = new ArrayList<>();
        List<String> skus = outOrderZiList.stream().map(OutOrderZi::getSkuCode).collect(Collectors.toList());
        LambdaQueryWrapper<Inventory> wrapper = Wrappers.lambdaQuery();
        wrapper.in(Inventory::getSkuCode, skus);
        wrapper.orderByAsc(Inventory::getInTime);
        List<Inventory> inventories = inventoryService.list(wrapper);

        for (String skuCode : outOrderZiList.stream().map(OutOrderZi::getSkuCode).collect(Collectors.toSet())) {
            int outQuantity = outOrderZiList
                    .stream()
                    .filter(data -> Objects.equals(data.getSkuCode(), skuCode))
                    .mapToInt(OutOrderZi::getNumber)
                    .sum();
            int inventoryQuantity = inventories
                    .stream()
                    .filter(data -> Objects.equals(data.getSkuCode(), skuCode))
                    .mapToInt(Inventory::getNumber)
                    .sum();
            Assert.isFalse(outQuantity > inventoryQuantity,
                    String.format("品番[%s]剩余库存数量[%s]，请勿多出", skuCode, inventoryQuantity));
        }

        Result<Object> result = getObjectResult(outOrderZiList, collect, inventories, addList);
        if (result != null) return result;
        OutOrder outOrder = new OutOrder();
        BeanUtils.copyProperties(outOrderPage, outOrder);
        outOrderService.saveMain(outOrder, addList);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param outOrderPage
     * @return
     */
    @AutoLog(value = "出库单-编辑")
    @ApiOperation(value = "出库单-编辑", notes = "出库单-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody OutOrderPage outOrderPage) {
        OutOrder outOrder = new OutOrder();
        BeanUtils.copyProperties(outOrderPage, outOrder);
        OutOrder outOrderEntity = outOrderService.getById(outOrder.getId());
        if (outOrderEntity == null) {
            return Result.error("未找到对应数据");
        }
        outOrderService.updateById(outOrder);
        outOrderZiService.updateBatchById(outOrderPage.getOutOrderZiList());
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "出库单-通过id删除")
    @ApiOperation(value = "出库单-通过id删除", notes = "出库单-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        outOrderService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "出库单-批量删除")
    @ApiOperation(value = "出库单-批量删除", notes = "出库单-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.outOrderService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "出库单-通过id查询")
    @ApiOperation(value = "出库单-通过id查询", notes = "出库单-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        OutOrder outOrder = outOrderService.getById(id);
        if (outOrder == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(outOrder);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "出库单子表通过主表ID查询")
    @ApiOperation(value = "出库单子表主表ID查询", notes = "出库单子表-通主表ID查询")
    @GetMapping(value = "/queryOutOrderZiByMainId")
    public Result<?> queryOutOrderZiListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<OutOrderZi> outOrderZiList = outOrderZiService.selectByMainId(id);
        return Result.OK(outOrderZiList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param outOrder
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, OutOrder outOrder) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<OutOrder> queryWrapper = QueryGenerator.initQueryWrapper(outOrder, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //Step.2 获取导出数据
        List<OutOrder> queryList = outOrderService.list(queryWrapper);
        // 过滤选中数据
        String selections = request.getParameter("selections");
        List<OutOrder> outOrderList = new ArrayList<OutOrder>();
        if (oConvertUtils.isEmpty(selections)) {
            outOrderList = queryList;
        } else {
            List<String> selectionList = Arrays.asList(selections.split(","));
            outOrderList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        }

        // Step.3 组装pageList
        List<OutOrderPage> pageList = new ArrayList<OutOrderPage>();
        for (OutOrder main : outOrderList) {
            OutOrderPage vo = new OutOrderPage();
            BeanUtils.copyProperties(main, vo);
            List<OutOrderZi> outOrderZiList = outOrderZiService.selectByMainId(main.getId());
            vo.setOutOrderZiList(outOrderZiList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "出库单列表");
        mv.addObject(NormalExcelConstants.CLASS, OutOrderPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("出库单数据", "导出人:" + sysUser.getRealname(), "出库单"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<OutOrderPage> list1 = ExcelImportUtil.importExcel(file.getInputStream(), OutOrderPage.class, params);
                List<BasicSku> basicSkus = basicSkuService.list();
                Set<String> collect = basicSkus.stream().map(BasicSku::getSkuCode).collect(Collectors.toSet());
                for (OutOrderPage page : list1) {
                    List<OutOrderZi> outOrderZiList = page.getOutOrderZiList();
                    List<OutOrderZi> addList = new ArrayList<>();
                    Set<String> skus = outOrderZiList.stream().map(OutOrderZi::getSkuCode).collect(Collectors.toSet());
                    LambdaQueryWrapper<Inventory> wrapper = Wrappers.lambdaQuery();
                    wrapper.in(Inventory::getSkuCode, skus);
                    wrapper.orderByAsc(Inventory::getInTime);
                    wrapper.orderByAsc(Inventory::getStatus);
                    List<Inventory> inventories = inventoryService.list(wrapper);
                    List<OutOrderZi> summarizedList = outOrderZiList.stream()
                            .filter(outOrderZi -> outOrderZi.getSkuCode() != null)
                            .collect(Collectors.groupingBy(OutOrderZi::getSkuCode,
                                    Collectors.collectingAndThen(
                                            Collectors.toList(),
                                            (Function<List<OutOrderZi>, List<OutOrderZi>>) list -> { // 显式指定Function的输入输出类型
                                                if (list.isEmpty()) return Collections.emptyList();
                                                OutOrderZi representative = new OutOrderZi();
                                                BeanUtils.copyProperties(list.get(0), representative);
                                                representative.setNumber(list.stream().mapToInt(OutOrderZi::getNumber).sum());
                                                return Collections.singletonList(representative);
                                            })
                            ))
                            .values()
                            .stream()
                            .flatMap(List::stream)
                            .collect(Collectors.toList());
                    Result<Object> result = getObjectResult(summarizedList, collect, inventories, addList);
                    if (result != null) return result;
                    OutOrder po = new OutOrder();
                    BeanUtils.copyProperties(page, po);
                    po.setOutTime(new Date());
                    outOrderService.saveMain(po, addList);
                }
                return Result.OK("文件导入成功！数据行数:" + list1.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }

    private static @Nullable Result<Object> getObjectResult(List<OutOrderZi> outOrderZiList, Set<String> collect, List<Inventory> inventories, List<OutOrderZi> addList) {
        for (OutOrderZi outOrderZi : outOrderZiList) {
            Result<Object> result = getObjectResult(outOrderZi, collect);
            if (result != null) return result;
            int number = outOrderZi.getNumber();
            String skuCode = outOrderZi.getSkuCode();
            for (Inventory inventory : inventories) {
                if (!inventory.getSkuCode().equals(skuCode)) continue; // 确保处理相同SKU的库存
                int stock = inventory.getNumber();
                if (stock == 0) continue;
                if (number >= stock) {// 如果待出库数量大于当前reportLabel对象的库存数量
                    number -= stock;
                    OutOrderZi outOrderZi1 = new OutOrderZi();
                    BeanUtils.copyProperties(outOrderZi, outOrderZi1);
                    outOrderZi1.setNumber(inventory.getNumber()).setLocation(inventory.getLocation())
                            .setInventoryId(inventory.getId()).setSkuName(inventory.getSkuName())
                            .setInventory(inventory.getNumber()).setInTime(inventory.getInTime());
                    addList.add(outOrderZi1);
                    stock = 0;
                } else {// 待出库数量小于当前reportLabel对象的库存数量
                    stock -= number;
                    OutOrderZi outOrderZi1 = new OutOrderZi();
                    BeanUtils.copyProperties(outOrderZi, outOrderZi1);
                    outOrderZi1.setNumber(number).setLocation(inventory.getLocation())
                            .setInventoryId(inventory.getId()).setSkuName(inventory.getSkuName())
                            .setInventory(inventory.getNumber()).setInTime(inventory.getInTime());
                    addList.add(outOrderZi1);
                    number = 0;
                }
                inventory.setNumber(stock);// 更新当前reportLabel对象的库存数量
                if (number == 0) {// 如果待出库数量已经为0，则跳出循环
                    break;
                }
            }
        }
        return null;
    }

    private static @Nullable Result<Object> getObjectResult(OutOrderZi outOrderZi, Set<String> collect) {
        String sku = outOrderZi.getSkuCode().replaceAll(" ", "");
        outOrderZi.setSkuCode(sku);
        if (!collect.contains(sku)) {
            return Result.error("入库单中【" + outOrderZi.getSkuCode() + "】品番不存在,若确认无误，请先维护品番数据");
        }
        return null;
    }

}
